Partial message streaming

ABSTRACT

Embodiments provided herein support large messages by formatting at least a portion of the message in the form of a transport stream. More specifically, embodiments provide a SOAP model that can stream an object for a message without loading the entire message into an intermediate buffer. Accordingly, one embodiment supports loading SOAP headers into memory, yet streaming the body. This would allow, for example, large attachments (e.g., a video file) to accompany the SOAP message in the body, while still supporting random access to message headers. Accordingly, embodiments provide a SOAP data model that allows a developer to create an object and specify whether or not portions of the message should be buffered or streamed.

CROSS-REFERENCE TO RELATED APPLICATIONS

This application claims priority to U.S. Provisional Application Nos.filed 60/764,124 and 60/764,306 filed Jan. 31, 2006 and Feb. 1, 2006,respectively, both entitled “MESSAGE OBJECT MODELING, FORMATTING, ANDENCODING”, the contents of each are incorporated herein by reference intheir entirety. This application also relates to the following U.S.patent application Ser. Nos. ______, ______, ______, ______, and ______,filed on the same day herewith and entitled “MESSAGE OBJECT MODEL”(Docket No. 13768.630.1.1), “SIMULTANEOUS API EXPOSURE FOR MESSAGES”(Docket No. 13768.630.1.2), “ANNOTATING PORTIONS OF A MESSAGE WITH STATEPROPERTIES” (Docket No. 13768.630.1.4), “MESSAGE CONTRACT PROGRAMMINGMODEL” (Docket No. 13768.630.1.5), and “VARYING OF MESSAGE ENCODING”(Docket No. 13768.630.1.6), respectively, the contents of each are alsoincorporated herein by reference in their entirety.

BACKGROUND

Computer networks have enhanced our ability to communicate and accessinformation by allowing one computer or device to communicate over anetwork with another computing system using electronic messages. Whentransferring an electronic message between computing systems, theelectronic message will often pass through a protocol stack thatperforms operations on the data within the electronic message (e.g.,parsing, routing, flow control, etc.). The Open System Interconnect(OSI) model is an example of a network framework for implementing aprotocol stack.

The OSI model breaks down the operations for transferring an electronicmessage into seven distinct layers, each designated to perform certainoperations in the data transfer process. While protocol stacks canpotentially implement each of the layers, many protocol stacks implementonly selective layers for use in transferring data across a network.When data is transmitted from a computing system, it originates at theapplication layer and is passed down to intermediate lower layers andthen onto a network. When data is received from a network it enters thephysical layer and is passed up to the higher intermediate layers andthen is eventually received at that application layer. The applicationlayer—the upper most layer—is responsible for supporting application andend-user processing. Further, within the application layer there mayreside several other layers (e.g., the Simple Open Access Protocol(SOAP) layer). Another layer incorporated by most protocol stacks is thetransport layer. An example of a transport layer is the TransmissionControl Protocol (TCP).

A system that relies heavily on such communication or stack protocol isknown as Web services. Web services have been a driving force inadvancing communications between computing systems and are turning theway we build and use software inside-out. More specifically, webservices let applications share data and—more powerfully—invokecapabilities from other applications without regard to how theseapplications where built; what operating systems or platform they runon; and what devices are used to access them. Web services are invokedover the Internet by means of industry-standard protocols includingSOAP, XML (eXtensible Markup Language), UDDI (Universal Description,Discovery and Integration), WSDL (Web Service Description Language),etc. Although web services remain independent of each other, they canloosely link themselves into a collaborating group that performs aparticular task.

Current web service technologies offer direct SOAP-message communicationbetween an initiator (e.g., a client) and an acceptor (e.g., a service).SOAP is a lightweight protocol intended for exchanging structuredinformation in a decentralized, distributed environment. It uses XMLtechnologies to define an extensible messaging framework providing amessage contract that can be exchanged over a variety of underlyingprotocols. SOAP provides a way to communicate between applicationsrunning on different operating systems, with different technologies andprogramming languages. Accordingly, SOAP is platform and languageagnostic, yet simple and extensible.

The current SOAP specification defines a message construct in anopen-ended manner. More specifically, SOAP defines a message to be anXML infoset with a set of optional message headers followed by a messagebody. The current specification, however, does not place anyrequirements on how to map objects (in the sense of object-orientedprogramming) to SOAP messages or back again. Further, it does not placeany requirements on how to map the SOAP infoset to raw octets (formessage transmission). In addition, it does not place any maximum sizeon a SOAP message. Accordingly, in order to implement SOAP and integrateit into an object-oriented programming model, these are all problems onemust solve.

BRIEF SUMMARY

The above-identified deficiencies and drawback of current messagemodeling systems are overcome through example embodiments of the presentinvention. For example, embodiments described herein provide forreducing the buffer requirements for sending messages. Note that thisSummary is provided to introduce a selection of concepts in a simplifiedform that are further described below in the Detailed Description. ThisSummary is not intended to identify key features or essential featuresof the claimed subject matter, nor is it intended to be used as an aidin determining the scope of the claimed subject matter.

In accordance with a first example embodiment, a distributed messagingsystem is provided that efficiently sends large messages by limiting theamount of the message that is loaded into an intermediate buffer beforesending across a wire to a destination node. In this embodiment, amessage is accessed that is to be sent across the wire to a destinationnode. Then, a first portion of the message is loaded into anintermediate buffer for random access thereto. Note, however, that asecond portion of the message, different from the first portion, isformatted in the form of a transport stream and streamed across a wireto the destination node without loading the second portion in theintermediate buffer in order to reduce buffer requirements for sendinglarge messages.

Another example embodiment provides for a distributed messaging systemthat reduces buffer requirements for processing a SOAP message byindexing headers as an array, while still providing random accessthereto. In this embodiment, a request to access content of a headerfrom a SOAP message during processing thereof. Next, an identifier isaccessed for the header within an index array, which includes a set ofheader identifiers used to map content of headers for the SOAP messageto a particular location within an original buffer. Based on a referencepointer corresponding to the identifier for the header, a location forthe content within the original buffer is determined. Wherein based onthe determined location, the original buffer is accessed for processinga portion of the content of the header without having to store entirecontent for the set of header identifiers as a data structure in anintermediate memory buffer.

In still another example embodiment, an index array of headeridentifiers is used to reduce buffer requirements for process a SOAPmessage, while still providing random access to header content. Theindex array comprising: (1) a set of header identifiers used in mappingcorresponding headers of a SOAP message with content stored in aoriginal buffer; and (2) a corresponding set of reference pointers usedto determine where within the original buffer content for each of theheaders are located such that at least a portion of the content can beprocessed without having to store entire content for each of the headersas a data structure in an intermediate memory buffer.

Additional features and advantages of the invention will be set forth inthe description which follows, and in part will be obvious from thedescription, or may be learned by the practice of the invention. Thefeatures and advantages of the invention may be realized and obtained bymeans of the instruments and combinations particularly pointed out inthe appended claims. These and other features of the present inventionwill become more fully apparent from the following description andappended claims, or may be learned by the practice of the invention asset forth hereinafter.

BRIEF DESCRIPTION OF THE DRAWINGS

In order to describe the manner in which the above-recited and otheradvantages and features of the invention can be obtained, a moreparticular description of the invention briefly described above will berendered by reference to specific embodiments thereof which areillustrated in the appended drawings. Understanding that these drawingsdepict only typical embodiments of the invention and are not thereforeto be considered to be limiting of its scope, the invention will bedescribed and explained with additional specificity and detail throughthe use of the accompanying drawings in which:

FIG. 1 illustrates a distributed system configured to utilize anopen-ended object model in accordance with example embodiments;

FIG. 2A illustrates the use of a message contract to create a generalmessage object in accordance with example embodiments;

FIG. 2B illustrates using a message formatter for communication with aservice operation in accordance with example embodiments;

FIG. 3 illustrates a flow diagram for a method of using a single messageobject to create message instances of multiple messaging formats inaccordance with example embodiments;

FIGS. 4A and 4B illustrate flow diagrams for methods of simultaneouslyexposing a message infoset as both an XML view and a Type view inaccordance with example embodiments;

FIG. 5 illustrates a flow diagram for a method of indexing headers for aSOAP message as an array in accordance with example embodiments;

FIGS. 6A and 6B illustrate flow diagrams for methods of efficientlyprocessing a SOAP message by attaching thereto properties representingprocessing state for portions of the message in accordance with exampleembodiments;

FIG. 7 illustrates a flow diagram for a method of formatting a layout ofa message object using a message contract in accordance with exampleembodiments;

FIG. 8 illustrates a flow diagram for a method of creating an instanceof a message object by using a message contract in accordance withexample embodiments;

FIG. 9 illustrates a flow diagram for a method of automatically creatinga NPDL contract in accordance with example embodiments; and

FIG. 10 illustrates a flow diagram for a method of determining a type ofencoding to use for a SOAP message in accordance with exampleembodiments.

DETAILED DESCRIPTION

The present invention extends to methods, systems, and computer programproducts for modeling, formatting, and encoding messages, e.g., SOAP, ina distributed system. The embodiments of the present invention maycomprise a special purpose or general-purpose computer including variouscomputer hardware or modules, as discussed in greater detail below.

Embodiments described herein generally relate to a messaging in adistributed system. A message provides the fundamental unit ofcommunication between endpoints in a distributed service system, e.g.,web services. That is, it is the container within which data exchangedbetween services is encapsulated. The structure of a message asdescribed herein loosely corresponds to that of the SOAP envelope. Amessage may contain both a set of message headers and a body, which cancorrespond to the SOAP Header blocks and the SOAP Body, respectively.Note that although some embodiments may be described in terms of SOAPprotocol, embodiments herein are not necessarily limited to SOAPmessaging unless otherwise explicitly claimed.

Regardless of the type of message, one embodiment as described ingreater detail below provides for an overall object model that allowsfor a single message object to represent multiple messaging formats. Inthis example, the general message object is populated with fields formultiple available messaging formats, which can be appropriately filledwith information depending on the desired format. For example, a SOAPobject may be provided with fields for both versions 1.1 and 1.2.Depending on which version is being used or desired, the appropriatefields can be populated when creating an instance of the message object.

In another embodiment, a message object is provided that simultaneouslyexposes an XML view and Type view for a message infoset. In thisembodiment, interaction with a message can occur using either an XML orType application program interface (API), which are synced. Morespecifically, embodiments herein provide or expose a common set ofheaders (e.g., SOAP headers) as “typed” properties (e.g., CLRproperties), which allow for getting and/or setting a value thereof. Inother words, the Type API reads/writes values for typed propertieswithout regard to how the message is encoded with XML. Moreover, the twoAPIs are synced such that a value can be set using one API and retrievedusing the other. For example, an XML API may be used as a writingmechanism for interacting with a value, while the Type API can read thatsame value, and vise-versa.

Embodiments provided herein also support large messages by formatting atleast a portion of the message in the form of a transport stream. Thatis, embodiments provide a SOAP model that can stream an object for amessage without loading the entire message into an intermediate buffer.Accordingly, one embodiment supports loading SOAP headers into memory,yet streaming the body. This would allow, for example, large attachments(e.g., a video file) to accompany the SOAP message in the body, whilestill supporting random access to message headers. Accordingly,embodiments provide a SOAP data model that allows a developer to createan object and specify whether or not portions of the message should bebuffered or streamed.

In yet another embodiment, the headers of a SOAP or other message may bereferenced using an in memory index. Accordingly, memory needed forbuffering a message may be further reduced, yet still providing forrandom access to the headers. In this embodiment, rather than using adocument object model (DOM) to store the content (e.g., attributes,elements, values, etc.) of each header, a set of references or an indexof headers (such as a header number) may be stored as a byte array.

Still other example embodiments provide that as a SOAP message isprocessed, various states known as properties can be attached to themessage for various purposes. In other words, embodiments provide for aproperties object that represents a set of processing-level annotationsto a message. These properties (representing the processing state of theheaders or other portions of the message) can then be used by othercomponent or modules for further processing purposes. Typically, theseproperties can then be removed (or sustained if desired) prior totransporting the SOAP message on the wire.

In another example embodiment, a message contract programming model isprovided, which is a mechanism for service developers to control theprocessing, layout, and creation of messages (e.g., SOAP) without losingthe benefits of a strongly-typed data contract model. Such programmingmodel is based on attributes, which can be used to define the action oroperations, headers, and body parts components of a message. Theseattributes may be used on a type annotated with message contract or on aservice operation to control the manner in which the message (e.g.,SOAP) is constructed from a service process, process parameters, and/orreturn values. The use of the message contract in conjunction with amessage formatter as defined herein provides for many advantageousfeatures and embodiments described in greater detail below.

Another embodiment as described herein allows a user to vary theencoding of a message object rather than being bound to a specific one,e.g., the text encoding for SOAP messaging. Accordingly, a messageencoding factory is provided that is responsible for mapping a messageobject (e.g., SOAP Infoset) into raw octets suitable for wiretransmission. By encapsulating the notion of a message encoder factoryabstractly, embodiments allow users to vary the encoding of an Infosetwithout varying the programming model (or any other aspect of the systemthat uses message). In other words, embodiments herein separate thetransport (e.g., TCP, HTTP, etc.) from the encoding, which allows usersto use any number of encoding mechanisms—even their own proprietaryones.

Although more specific reference to advantageous features are describedin greater detail below with regards to the Figures, embodiments withinthe scope of the present invention also include computer-readable mediafor carrying or having computer-executable instructions or datastructures stored thereon. Such computer-readable media can be anyavailable media that can be accessed by a general purpose or specialpurpose computer. By way of example, and not limitation, suchcomputer-readable media can comprise RAM, ROM, EEPROM, CD-ROM or otheroptical disk storage, magnetic disk storage or other magnetic storagedevices, or any other medium which can be used to carry or store desiredprogram code means in the form of computer-executable instructions ordata structures and which can be accessed by a general purpose orspecial purpose computer. When information is transferred or providedover a network or another communications connection (either hardwired,wireless, or a combination of hardwired or wireless) to a computer, thecomputer properly views the connection as a computer-readable medium.Thus, any such connection is properly termed a computer-readable medium.Combinations of the above should also be included within the scope ofcomputer-readable media.

Computer-executable instructions comprise, for example, instructions anddata which cause a general purpose computer, special purpose computer,or special purpose processing device to perform a certain function orgroup of functions. Although the subject matter has been described inlanguage specific to structural features and/or methodological acts, itis to be understood that the subject matter defined in the appendedclaims is not necessarily limited to the specific features or actsdescribed above. Rather, the specific features and acts described aboveare disclosed as example forms of implementing the claims.

As used herein, the term “module” or “component” can refer to softwareobjects or routines that execute on the computing system. The differentcomponents, modules, engines, and services described herein may beimplemented as objects or processes that execute on the computing system(e.g., as separate threads). While the system and methods describedherein are preferably implemented in software, implementations inhardware or a combination of software and hardware are also possible andcontemplated. In this description, a “computing entity” may be anycomputing system as previously defined herein, or any module orcombination of modulates running on a computing system.

FIG. 1 illustrates a distributed system 100, wherein a client 105 sendsrequests messages 10 to a service 155, which replies with responsemessages 150. Note that although embodiments are described in terms of arequest-response protocol, other message exchange patterns are alsocontemplated herein. Regardless of the type of exchange pattern,embodiments described herein provides for an overall message objectmodel that allows for efficiently representing, processing, formatting,and encoding messages. Note that the following description ofembodiments provided herein will occasionally refer to components andmodules from FIG. 1. Note, however, that other configurations anddesigns choices are also available to embodiments described herein, andas such the modules and layout of the distributed system in FIG. 1 isfor illustrative purposes only.

A message e.g., request message 110, or response message 150, providesthe fundamental unit of communication between endpoints 105, 155 in adistributed service system 100, e.g., web services. That is, it is thecontainer within which all data exchange between services isencapsulated. The structure of a message loosely corresponds to that ofthe SOAP envelope. A message contains both a set of message headers anda body, which can correspond to the SOAP header blocks and the SOAPbody, respectively.

One problem associated with current messaging models is that in order tocommunicate with messages that support multiple format protocols, oneneeds to create code paths for the various formats provided. Forexample, when creating a SOAP message envelope, one needs to specify andsupport a particular version of the SOAP message (e.g., v. 1.1 or 1.2).As multiple formats are extended, however, the code breaks and must bemodified for supporting such updates. Accordingly, embodiments providefor an object model that defines a single message class or object forrepresenting multiple message format protocols.

Such object model includes multiple fields that support each of themultiple formats. For example, if one version or format of a messagerequires or supports fields A, B, and D, while another one requires orsupports C, D, and E, the single message class should include fields forA, B, C, D, and E. Those fields that do not apply to a format desiredfor a message can be ignored. Accordingly, the single object can be usedto create a message for a specific format as needed. In other words, asa user creates a message, or as a stream of data is received forcompilation into a message, the single message object can be used tocreate a format specific message based on the supported formats therein.

Another problem with current message object models is that the messageinfoset is exposed as an XML data object. Accordingly, XML APIs (i.e.,XML readers/writers) are used for processing a message, e.g., SOAP,which must create XML data objects for each port of the XML content. Byreducing the overall allocation per message, however, embodiments hereinallow for improved performance considerations.

For example, a common way to represent a SOAP Infoset as an instance orimplementation of a common language infrastructure (CLI) object (e.g., acommon language runtime (CLR) object) would be in terms of the basic XMLAPIs (e.g., XmlReader/XmlWriter). For instance, one can retrieve thevalue of a web service addressing “ReplyTo” header as follows:

 // Option 1:  int index = message.Headers.FindHeader(“ReplyTo”,“http://schemas.xmlsoap.org/ws/2004/08/addressing/”); XmlDictionaryReader reader =  message.Headers.GetReaderAtHeader(index); EndpointAddress ReplyTo = EndpointAddress.ReadFrom(reader);In this example, first an index to the header is found via the XMLqualified name or QName (name, namespace). Next, an XmlDictionaryReader(a specialization of XmlReader) is retrieved for that particular header,which is then passed into the EndpointAddress.ReadFrom( . . . ) methodto create a typed representation of that header.

Embodiments herein not only support the above mechanism for interactingwith a value within a message, but also provide a “Type” API for aninfoset that reads/writes values for typed properties without regard tohow the message is encoded with XML. In other words, embodiments hereinprovide or expose a common set of headers (e.g., SOAP headers) as“typed” properties (e.g., CLR properties), which allow for gettingand/or setting a value thereof. For example, the above equivalent ofretrieving the value of a web service addressing “ReplyTo” header cannow be accomplished using something similar to the following:

// Option 2: EndpointAddress ReplyTo = message.Headers.ReplyTo;

Note that embodiments simultaneously expose both the XML and Type APIs,and the two can be synced and used such that they can mismatch thereading/writing of a message. More specifically, a value can be setusing one API and retrieved using the other. For example, from theabove, the ReplyTo header may be created using the XML APIs, and thevalue thereof can then be retrieved using type propertymessage.Headers.ReplyTo, and vice-versa. Accordingly, one can interactwith these common headers within an infoset with either API, dependingon their preference. Note that although the typed property is shown as auniform resource identifier (URI) string, other types are also availableto this and other embodiments described herein.

Another problem with current messaging models is that a complete messagemust be buffered before it can be sent across the wire. As such,messages of large size require large memory, which may put some sizelimitations on a SOAP message and consume large amounts of valuablesystem resources. In other words, a large message may not be fullyrepresented in memory at one moment in time, which is to say that thesize of the message is larger than the memory available to the serviceprocessing the message. This memory limitation may be due to thephysical limitations of an endpoint such as the node hosting the serviceor some configured maximum buffer size specified by the service orendpoint.

Accordingly, embodiments provided herein support large messages byformatting at least a portion of the message in the form of a transportstream. That is, embodiments provide a SOAP model that can stream anobject for a message without loading the entire message into anintermediate buffer. Accordingly, one embodiment supports loading SOAPheaders into memory, yet streaming the body. This would allow, forexample, large attachments (e.g., a video file) to accompany the SOAPmessage in the body, while still supporting random access to messageheaders. Accordingly, embodiments provide a SOAP data model that allowsa developer to create an object and specify whether or not portions ofthe message should be buffered or streamed.

Note that this embodiment of SOAP message streaming involves the use ofa transport connection (TCP socket, named pipe, HTTP connection) that istypically dedicated to stream the message. Accordingly, in order to makeof use transport streaming, the transports utilized by a client andserver should be configured to support streaming. This may be done,e.g., via a transfer mode property of a channel factory and/or channellistener (e.g., TCP, named pipe, HTTP, or other transportchannel/factory setting). Of course other mechanisms for setting thisfeature are also contemplated herein. For example, this feature may alsobe enabled via the transport binding elements (e.g.,TcpTransportBindingElement, NamedPipeTransportBindingElement,HttpTransportBindingElement, etc.). In addition, transport streaming maybe enabled via the service binding or by some other mechanism.Accordingly, the above mechanisms used for enabling the embodiment ofstreaming a message are used herein for illustrative purposes and arenot meant to limit or otherwise narrow the scope of these embodiments.

In one embodiment, a transport connection is closed at the conclusion ofa message transmission in order to notify the receiver that thetransmission is complete. Note that in such case, streaming may belimited to use with certain channel types. Nevertheless, embodimentsherein support multiple transports and exchange patterns. For example,when utilizing TCP or named pipes, request/reply channel, output/inputchannel (which can be built on top of request/reply channel) or fullduplex channel (which uses a pair of output/input channels) may besupported. Further, when utilizing HTTP request/reply channels orrequest/reply session channels may be supported. Of course, othertransports and exchange patterns are also supported herein. Note,however, that when streaming is configured for a given contract/binding,embodiments automatically ensure that the proper channel type can berequested and created.

Note that there may be some limitations that developers should considerwhen using this above streaming model for SOAP messages. For example,some security, reliability, and/or other protocols may not be supportedwhen streaming a message. For example, some web service securityprotocols require the whole message to be buffered and some reliabilityprotocols require the message be completely read before sendingacknowledgements. Nevertheless, embodiments provide that the transportsecurity and/or reliability may need to be used with streaming in orderto overcome some of these limitations.

The following provides some pseudo-code for a SOAP message transportstreaming API and some streaming examples. Note that the following areexamples only and are not meant to limit or otherwise narrow the scopeof embodiments unless otherwise explicitly claimed.

Transport Streaming API Example

namespace System.ServiceModel {   // Existing class   public classMessage   {     //Pulls the data from the provided XmlReader to populatethe     body static public Message CreateMessage(string action,    XmlReader body);     //Allows the developer to write directly to thebody (push)     static public Message CreateMessage(string action,    IBodyWriter writer);     //same as above, but takes a messageversion     static public Message CreateMessage(MessageVersion version,string action, XmlReader body);     static public MessageCreateMessage(MessageVersion version, string action, IBodyWriterwriter);   }   //implemented by the developer enable the push scenario  //Message will call the WriteBody implementation when the Message iswritten out   interface IBodyWriter   {     void WriteBody(XmlWriterwriter);   }   //Existing class   public classTcpTransportBindingElement :   TransportBindingElement   {     //Allowsthe developer to state if the transport supports     streaming    //Buffered may be the default     public TransferMode Mode { get;set; }   }   //Existing class   public classNamedPipeTransportBindingElement :   TransportBindingElement   {    //Allows the developer to state if the transport supports    streaming     //Buffered may be the default     public TransferModeMode { get; set; }   }   public class HttpTransportBindingElement :  TransportBindingElement   {     //Allows the developer to state if thetransport supports     streaming     //Buffered may be the default    public TransferMode Mode { get; set; }   } } namespaceSystem.ServiceModel.Channels {   //TransferMode is typed to this enum  public enum TransferMode   {     Buffered,     Streamed,    StreamedRequest,     StreamedResponse,   } }

Transport Streaming Examples

[ServiceContract] public interface IPurchaseOrderContract {   //use amessage directly   [OperationContract(IsOneWay = true)]   voidProcessLargeOrder(Message msg); }  class PurchaseOrderProxy :ClientBase< IPurchaseOrderContract>, IPurchaseOrderContract  {  publicPurchaseOrderProxy( )   : base( )  {  }  public PurchaseOrderProxy(string configurationName)   : base(configurationName)  {  }  publicPurchaseOrderProxy (Binding binding, EndpointAddress address)   :base(binding, address)  {  }  public void ProcessLargeOrder(Messagemessage)   {   base.InnerProxy. ProcessLargeOrder(message);   }  } classPurchaseOrderService : IPurchaseOrderContract  {   public static voidMain( )   {     ServiceHost service = newServiceHost(typeof(PurchaseOrderService), “net.tcp://localhost/”);    //configure the transport to use streaming   Binding streamedBinding= new NetTcpBinding( );   streamedBinding.TransferMode =TransferMode.Streamed;  service.AddServiceEndpoint(typeof(IPurchaseOrderContract),streamedBinding, “/IPurchaseOrderService”);     service.Open( );    PurchaseOrderProxy server = new PurchaseOrderProxy(streamedBinding,new EndpointAddress(“net.tcp://localhost/IPurchaseOrderService/”));    //open a stream to a large business document on disk     using(XmlTextReader reader = new XmlTextReader(@“d:\po.xml”))     {      //set message body       Message msg =Message.CreateMessage(“http://processlargeorder”, reader);      //stream the data to the server      server.ProcessLargeOrder(msg);     }   }   public voidProcessLargeOrder(Message msg)   {     XmlReader reader =msg.GetBodyReader( );     while (reader.Read( ))     {      Console.WriteLine(reader.Value);     }   } } [ServiceContract]public interface IMovieContract {   [OperationContract]   MessageGetMovie(string movie); }  class MovieProxy : ClientBase<IMovieContract>, IMovieContract  {  public MovieProxy( )   : base( )  { }  public MovieProxy(string configurationName)   :base(configurationName)  {  }  public MovieProxy(Binding binding,EndpointAddress address)   : base(binding, address)  {  }  publicMessage GetMovie(string movie)  {   Returnbase.InnerProxy.GetMovie(movie);  }  } class MovieService :IMovieContract {   public static void Main( )   {     ServiceHostservice = new ServiceHost(typeof(MovieService),“net.pipe://localhost/”);   Binding streamedBinding = newNetNamedPipeBinding( );   streamedBinding.TransferMode =TransferMode.Streamed;  service.AddServiceEndpoint(typeof(IMovieContract), streamedBinding,“/IMovieService”);     service.Open( );     MovieProxy server =      new MovieProxy(streamedBinding, newEndpointAddress(“net.pipe://localhost/IMovieService/”));     //ask forthe movie and get the message     Message msg =server.GetMovie(“pulp_fiction.mpeg”);     //get a reference to thereader     XmlDictionaryReader reader = msg.GetBodyReader( );    //pulls the data from the stream and unencodes the bytes (methodomitted - see StreamBodyWriter to send side)     ShowMovie(reader);   }  public Message GetMovie(string movie)   {     //open a stream to themovie     FileStream stream = File.OpenRead(movie);     //createIBodyWriter implementation that copies from the Stream to the XmlWriter    //send the message     returnMessage.CreateMessage(“http://GetMovieResponse”, newStreamBodyWriter(stream));   } } //Copies the data from a stream to anXmlWriter public class StreamBodyWriter : IBodyWriter {   Stream_stream;   public StreamBodyWriter(Stream stream) { _stream = stream; }  public void Write(XmlWriter writer)   {     int blockSize = 4096;    int bytesRead = 0;     byte[ ] block = new byte[blockSize];     do    {       bytesRead = _stream.Read(block, 0, blockSize);      writer.WriteBase64(block, 0, bytesRead);     } while (bytesRead >0);   } }

In yet another embodiment, the headers of a SOAP or other message may bereferenced using an in memory index. As such, memory needed forbuffering a message may be further reduced, yet still providing forrandom access to the headers. In this embodiment, rather than using adocument object model (DOM) to store the content (e.g., attributes,elements, values, etc.) of each header, a set of references or an indexof headers identifiers (e.g., name and/or namespace) may be stored andthe contents of the message stored as a byte array. In other words,rather than taking the original buffer and transforming it into someother completely separate data structure, embodiments reference theoriginal buffer as an array by maintaining the header information in anindex. For example, the Qname of the header and a reference for whatorder the header appears in may be used as the reference number foraccessing the header. Accordingly, when the XML reader (or writer as thecase may be) needs to access the header, the reference number can beretrieved and the contents for the header accessed based thereon. As canbe seen, because embodiments are able to randomly access and readheaders on the fly, without building up an intermediate data structurefor the contents of the headers, this feature provides for someimportant performance enhancements.

Still other example embodiments provide that as a SOAP message isprocessed, various states known as properties can be attached to themessage for internal and external purposes. In other words, embodimentsprovide for a properties object that represents a set ofprocessing-level annotations to a message. These properties(representing the processing state of the headers or other portions of amessage) can then be used by other component or modules for furtherprocessing purposes. For example, such things as whether a message issecure, the message identifier, or other information may be attached asa property to the message. Typically, these properties can then beremoved (or sustained if desired) prior to transporting the SOAP messageon the wire. Accordingly, these properties provide for processingefficiencies, yet also allow for applying these efficiencies in aconfidential and secure manner.

For example, as a message makes it way through the Channelinfrastructure, it passes through a number of logically separateprocessing entities. For instance, a message that is part of a messagingstream may potentially pass through a message formatter 120, 145, atransport-level channel, any channel extensions that are installed, areliable messaging channel, any channel extensions that are installedthere, the streaming channel, a dispatcher 140, etc. Embodiments hereinallow a piece of code that processes a message to annotate it with theresults of that processing. Accordingly, message properties can appearas an annotation to the message and are typically stored as a set ofname ->object mappings in a properties object on message.

As noted above, properties typically represent the processing state ofheaders of a message; however, they can also represent processing stateof other portions of a message. For example, the properties may relateto the body or relate to environmental information about how a messagewas received off the wire (e.g., local IP address, TCP vs. UDP, HTTPheaders, etc. In addition, note that a message property may be marked toindicate that either it should or should not persist in the message uponserialization. This may be done either by the user or automatically bythe system. Note that a default may also be set, such that a property orstate information that is not specifically marked is removed or lostupon or before serialization. This may be an appropriate decision if themessage property contains sensitive key information, for instance.

Also note that one distinction between headers and properties (otherthan the one that headers are remain upon serialization) is that headersare typically version specific, where properties are version neutral.For example, by inspecting an addressing header directly, it maypreclude talking to endpoints of a specific web service addressingversion. Properties, on the other hand, are not version dependent, thusminimizing code needed to understand different versions or formats.

The following gives an example of a class used to set and/or get messageproperties in accordance with example embodiments. As with otherpseudo-code provided herein, the following is one of many example designpatterns to make setting/getting properties; however, suchimplementation is not meant to limit the scope of the propertyembodiment described herein.

class FooProperty {  public static string PropertyName { get { return“Foo”; } }  public static FooProperty Get(Message message)  {   return(FooProperty)    message.Properties.[PropertyName];  }  public staticvoid Set(Message message, FooProperty property)  {   returnmessage.Properties[PropertyName] = property;  } }

In another example embodiment, a message contract programming model isprovided, which is a mechanism for service developers to control theprocessing, layout, and creation of messages (e.g., SOAP) without losingthe benefits of a strongly-typed data contract model. Such programmingmodel is based on attributes (e.g., CLR attributes), which can be usedto define the action or operations, headers, and body part components ofa message. These attributes may be used on a type annotated with messagecontract or on a service operation to control the manner in which themessage (e.g., SOAP) is constructed from a service process, processparameters, and/or return values. The use of the message contract inconjunction with a message formatter 120, 145 as defined herein providesfor many advantageous features and embodiments.

For example, the message contract may be used to generate a generalmessage object. For instance, as shown in FIG. 2A, a message contract205 defined by a contract attribute provides a class with variouselements 210, 225 (e.g., types or structs with fields, properties,and/or events). A developer is allowed to decorate such elements with aheader attribute 215 or body attribute 220. Message formatter 230 canthen parse the message contract 205 to generate a general message object240. More specifically, message formatter 230 serializes (ordeserializes as the case may be) the envelope of the general messageobject 240 with headers and body element types (e.g., fields,properties, events, etc.) as defined by the contract attributes.

For instance, a developer may define a contract 205 for a general classof person, which includes elements of first name, last name, age, etc.By attaching the header attribute to these elements and processing themessage contract 205 using message formatter 230, a message object of aperson can be created or serialized that includes header tags withelement fields and properties for each of a first name, last name, age,etc.

It should be noted that although embodiments herein discuss separatemodules for message layout and wire transformation (i.e., formatters120, 145 and message encoder factories 125, 135), these and othermodules may be combined into a single component, and thusinterchangeable. Nevertheless, the term “formatter” will typically beused to describe the layout of a message or message object (i.e., theserialization/deserialization of how the message looks), whereas the“encoding” of a message will typically describe how the message looks onthe wire or communication channel. Encoding is also used herein to referto transforming messages to various types, e.g., SOAP, SMTP, MSMQ, etc.

In another embodiment, the message contract 205 may be used inconjunction with message values to create an instance output message. Inother words, by providing values to the mappings of the attributes forthe message contract 205, an instance of the message object 240 can becreated. For example, as shown in FIG. 2B, message values 245 andmessage contract 205 may be received as inputs to message formatter 230.Type message converter or message formatter 230 can then populate amessage object (e.g., message object 240) with the values provide tocreate an instance output message 250.

For example, using again the above person infoset class with elements offirst name, last name, and age, message values 245 may define one set ofthese elements as Jim, Jones, and 25, respectively. As such, bydecorating the message contract 205 with the appropriate headerattributes 215 for the corresponding elements, and providing theformatter with a message 245 that defines the values for these elements,an output message 250 can be automatically generated as XML (or typeproperties as noted above) headers similar to the following:

<envelope>   <headers>     <first_name>Jim</first_name>    <last_name>Jones</last_name>     <age>25</age>     ...   </headers>  <body>...</body> </envelope>

Such message may then be used by an endpoint (e.g., service operation260) for desired processing purposes.

Note that although the above/subsequent formatting examples where/aredescribed generally in terms of serialization (i.e., creation of amessage), embodiments used herein also apply to deseralization, just inreverse ordering of processing. For example, in the above creation ofthe output message 250, the output message 250 in conjunction with themessage contract 205 may be used to extract message values 245. Ofcourse as one would recognize, and as described in greater detail below,other uses of the message formatter 230 and the object models usedherein may also be applied to a deserialization process. Accordingly,any specific reference to the type of formatting(serialization/deserialization) is used herein for illustrative purposesonly and is not meant to limit the claims herein.

Note that the message contract programming model described herein alsoallows a developer to control the manner in which an operation'sparameters (service inputs) and return values (service output) areserialized/deserialized to/from headers and body parts of a message.Accordingly, similar to above, a data contract parameter(s) or returnvalue(s) may be annotated with a header or body attribute for specifyingor controlling various aspects of the message. In one embodiment,parameters and return values without message contract 205 attributes215, 220 are subject to a default serialization/deserializationrule(s)—e.g., wrapped and placed as a list within the body (e.g., childof a SOAP body); however, other defaults (e.g., placing them in aspecial header) are also contemplated herein.

In another embodiment, message contract 205 may be used to automaticallycreate a network protocol description language (NPDL) document for aservice 155 (e.g., WSDL document, XSD (XML Schema Definition), or othercontracts). A client 105 can use such document to determine how toappropriately format a message for requesting 10 offered serviceoperations 260. Accordingly, the message contract 205 provides a singleattribute for both the serialization/deserialization and also fordescribing the NPDL contract 275. Further, the message contract 205 mayinclude additional metadata that can also be used to generate theappropriate NPDL contract 275 operations/messages/message parts, whichcan then be retrieved from contract store 280 and used by client 270 forcommunicating with service operation 260.

The following describes in greater detail the general formatting (e.g.,creation and use of message contract) embodiments described above. Notethat although reference to a specific implementation (e.g., namingconvention) may be used, such use is meant for illustrative purposesonly.

As previously mentioned, a message contract 205 is an abstract contractdescribing the message format or layout (e.g., SOAP message headers andbody parts). One or more of the following conditions may be needed for atype (e.g., CLR type) to implement a message contract: (1) the typeshould be annotated with the message contract attribute; (2) fieldsand/or properties to be included in the message contract should haveeither message header or message body attributes; (3) zero or morefields/properties can have message body attribute; (4) zero or morefields/properties can have nessage body attribute; (5) one or morefields or properties can be of type list type for an XML element andhave a message headers attribute; and in addition, such fields and/orproperties should be typed to one of the primitive types supported by adata contract or a type that implements the data contract. The followinggives some examples of some of the above conditions.

As previously mentioned, defining a message contract 205 is a matter ofdecorating a class (e.g., with message contract attribute and decoratingone or more of the class's elements (e.g., fields or properties) withmessage body and/or header attributes. For example the following definesa generalized message contract 205:

[MessageContract(ActionUri=“http://createpersonrequest”)]Name=“CreatePersonRequest”)] public sealed class CreatePersonRequest {  [MessageBody(NamespaceUri = “http://namespace”,    Name = “MyData”,Position = 2)]   public string OptionalData;   [MessageBody(NamespaceUri= “http://namespace”,    Name = “TheList”)]   public List<int> Ids; }that when formatted and populated with values can map to the followingSOAP message:

<soap:Envelope  xmlns:soap=‘http://schemas.xmlsoap.org/soap/envelope/’ xmlns:wsa=‘http://schemas.xmlsoap.org/ws/2004/03/addressing’> <soap:Header>   <!-- ... other headers omitted for brevity -->  <wsa:Action>http://createpersonrequest</wsa:Action>  </soap:Header> <soap:Body xmlns:x=‘http://namespace’>    <x:TheList>    <x:Item>5</x:Item>     <x:Item>10</x:Item>    </x:TheList>   <x:MyData>some data here</x:MyData>  </soap:Body> </soap:Envelope>

In order to use a message contract type in an operation or process, theoperation should have at least one (and possibly only one) parameter.Further, both the return type and the parameter type, if present, shouldbe message contract types. For example, suppose that BankingTransactionand BankingTransactionResponse are both types that have messagecontracts. Then, the following operations are typically consideredvalid:

[OperationContract] BankingTransactionResponseProcess(BankingTransaction bt); [OperationContract] voidStore(BankingTransaction bt); [OperationContract]BankingTransactionResponse GetResponse( );

Note that another embodiment also provides that if a type has both amessage contract and a data contract, then the message contract isconsidered when the type is used in an operation. Note, however, thatthe opposite result may also apply, i.e., the data contract may beconsidered when the type is used in the operation.

As previously mentioned, embodiments define a message contract 205 for atype (i.e. define the mapping between the type and a message (e.g.,SOAP) envelope), by allowing a developer to apply the message contractattribute to the type. Further, embodiments allow a developer to applythe message header attribute to those members or elements of the typefor which message (e.g., SOAP) headers are desired, and also allow adeveloper to apply the message body attribute to those members orelements that are targeted for parts of the message body. For example,consider the following type that has been made into a message contract205:

[MessageContract] public class BankingTransaction {   [MessageHeader]public Operation operation;   [MessageBody] private AccountsourceAccount;   [MessageBody] private Account targetAccount;  [MessageBody] public int amount; }

When using this class or type as an operation parameter, a SOAP envelopecan be generated with an extra header called “operation”, “process”, orthe like, which will typically include the contents of the “operation”field. On the other hand, a message or SOAP body should include thecontents of the “sourceAccount”, “targetAccount”, and “amount” fields.For example, the above message contract may result in the following XMLmessage:

<header>  <operation>some action</operation> </header> <body> <sourceAccount>some data</sourceAccount>  <targetAccount>somedata</targetAccount>  <amount>some data</amount> </body>

Notice that the default name for entries in this example is the name ofthe member or element to which the message header or body attribute isapplied. As will be described in greater detail below, however, otherembodiments allow for the name to be specified using a naming propertyon a portion of the message class. Also note that the message header andbody attributes can be applied to all fields, properties, and events,regardless of whether they are public, private, protected or internal.

Other embodiments provide that the order of the header or body elementsmay have a default setting, e.g., alphabetical, but may be controlled byan order property on message header or body attribute. For instance, inthe example above, “amount” would come first since it is firstalphabetically. To have the body order “sourceAccount”, then“targetAccount”, and then “amount”, the message contract may be changeto something similar to the following:

[MessageContract] public class BankingTransaction {   [MessageHeader]public Operation operation;   [MessageBody(Order=1)] public AccountsourceAccount;   [MessageBody(Order=2)] public Account targetAccount;  [MessageBody(Order=3)] public int amount; }Note, however, that there are other mechanisms and syntactics forordering or otherwise positioning how elements will map to the message.Accordingly, the above is used for illustrative purposes only and is notmeant to limit or otherwise narrow the scope of this embodiment.

Other embodiments also allow for the message header and body attributesto apply to arrays of repeating elements in message contracts. Forexample, one way to use a message header and/or body attribute is toannotate it directly on the array. In such case, the entire array can beserialized as one element (i.e. one header or one body part) withmultiple child elements. For example, consider the following class:

[MessageContract] public class BankingDeopsitLog {   [MessageHeader]public int numRecords   [MessageHeader] public DepositRecord records[ ];  [Messageheader] public int branchID; }This class when given specific values can result in an XML message bodysimilar to the following:

<numRecords>3</numRecords> <records>  <DepositRecord>Record1</DepositRecord>  <DepositRecord>Record2</DepositRecord>  <DepositRecord>Record3</DepositRecord> </records><branchID>20643</branchID>

As an alternative to the above, other embodiments provide for a messageheader or body array attribute. In this case, each array element can beserialized independently, and thus there will be one header or one bodypart per array element. For example, consider the following class:

[MessageContract] public class BankingDeopsitLog {   [MessageHeader]public int numRecords   [MessageHeaderArray] public DepositRecordrecords[ ];   [MessageHeader] public int branchID; }This may result in a SOAP or body similar to the following:

<numRecords>3</numRecords> <records>Record1</records><records>Record2</records> <records>Record3</records><branchID>20643</branchID>Notice that the default name for array entries is the name of the memberto which the message header and/or body array attribute is applied.Similar to above, however, such default may be overridden by applying anaming property on a portion of the message contract, e.g., messageheader and/or body array attribute.

Embodiments also provide that the message header and/or body arrayattributes inherit from the message header and/or body attributes,respectively. Thus, they have a similar set of features as the non-arrayattributes. For example, it is possible to set the order, name, and/ornamespace for an array of headers/body parts in similar manner as notedabove for a single header/body part. Note, however, that when the orderproperty is used on an array, it typically applies to the entire arrayas a whole—although other embodiments also allow for a mechanism forordering each element within the array.

Other embodiments provide that byte arrays, when used with the non-arrayattributes (message header and/or body attributes), may not be treatedas arrays but as a special primitive type represented as base64-encodeddata in the resulting XML. On the other hand, when byte arrays are usedwith the array attributes (message header and/or body array attributes),the results may vary. For example, one embodiment allows for the arrayto be represented as an individual entry for each byte. Anotherembodiment, however, provides that byte arrays can be treated as base64data regardless of whether the array or non-array attributes are used.For example, consider the following class:

[MessageContract] public class ProductData {   [MessageBody] byte[ ]Image;   [MessageBodyArray] byte[ ] productCode; }Assuming that the array is to be represented as an individual entry foreach byte, the message body may look similar to the following:

<Image>p4m2rrULt3f==</Image> <productCode>32</productCode><productCode>255</productCode> <productCode>17</productCode>

Still other embodiments allow a message contract to indicate whether theheaders and/or the body of the message should be digitally signed andencrypted. For example, provided herein is a setting of a protectionlevel property on the message header and/or body attributes. Note thatone embodiment provides that the property can be set to none (noencryption or signature), sign (digital signature only), or encrypt andsign (both encryption and a digital signature). The default may be none.For these security features to work, the binding and behaviors may haveto be properly configured. Embodiments provide that an exception may bethrown if use fo these security features is attempted without a properconfiguration (for example, attempting to sign a message withoutsupplying your credentials).

The protection level may be determined for each header individually. Thebody, however, typically has one protection level regardless of thenumber of body parts—although embodiments consider setting differentlevels for different body parts. Further, one embodiment provides thatthe protection level of the body can be determined by the highestprotection level property setting of all the body parts. For example,consider the following class:

[MessageContract] public class PatientRecord {  [MessageHeader(ProtectionLevel=None)] public int recordID;  [MessageHeader(ProtectionLevel=Sign)] public string patientName;  [MessageHeader(ProtectionLevel=EncryptAndSign)] public string SSN;  [MessageBody(ProtectionLevel=None)] public string comments;  [MessageBody(ProtectionLevel=Sign)] public string diagnosis;  [MessageBody(ProtectionLevel=EncryptAndSign)] public stringmedicalHistory; }In this example, the recordID header will not be protected, patientNamewill be signed, and SSN will be encrypted and signed. There is at leastone body part, medicalHistory, with encrypt and sign, and thus the aboveembodiment provides that entire message body should be encrypted andsigned, even though the comments and diagnosis body parts specify lowerprotection levels. As noted above, however, embodiments do allow for theindividual portions of the body to be secured by the various protectionlevels.

As previously noted in the message (e.g., SOAP) representation of amessage contract, each header and body part maps to an XML element whichtypically has a qualified name (e.g., Qname including name and anamespace). One embodiment provides that by default, the namespace canbe the same as the namespace of the service contract that the message isparticipating in, and the name can be determined by the member orelement name to which the message header and/or body attributes areapplied. Of course, other embodiments allow the defaults to be changedby manipulating name and/or namespace properties of the either themessage header/body attributes or the message contract elementattribute, which is the parent class of the message header/bodyattributes. For example, consider the following class:

[MessageContract] public class BankingTransaction {   [MessageHeader]public Operation operation;  [MessageHeader(Namespace=”http://schemas.contosobank.com/auditing/2005”)] public bool IsAudited;   [MessageBody] public AccountsourceAccount;   [MessageBody] public Account targetAccount;  [MessageBody(Name=”transactionAmount”)] public int amount; }

In this example, the IsAudited header will be in the namespace specifiedin the code, and the body part representing the “amount” member will berepresented by an XML element with the name “transactionAmount”.

Note that SOAP and related web services standards define a propertycalled “action” that can be present for every SOAP message sent.Accordingly, embodiments herein provide that the value of this propertyis controllable. For example, the action property may either becontrolled through an operation contract attribute, or by setting theaction property on the message contract attribute that is applied to themessage contract type used in the operation. If both are set, theembodiments provide that a default one may be used, for example, themessage contract attribute action setting can be used.

The SOAP standard defines the following attributes that may exist on aheader: Actor/Role (Actor in SOAP 1.1, Role in SOAP 1.2);MustUnderstand; and Relay. The Actor or Role attribute specifies the URIof the node for which a given header is intended. The MustUnderstandattribute specifies whether or not the node processing the header mustunderstand it. The Relay attribute specifies whether the header is to berelayed to downstream nodes.

Embodiments herein provide for not performing processing on one or moreof these attributes on incoming messages. One exception, however, may bethe MustUnderstand attribute as specified below in the section thatdiscusses message contract versioning. Nevertheless, embodiments allow adeveloper to read and write these attributes as they wish, as describedbelow.

One embodiment states that when sending a message, these attributesshould not be emitted by default. Other embodiments, however, providemechanisms to change this. For example, one embodiment allows forstatically setting the attributes to any desired values by changing theActor, MustUnderstand, and/or Relay properties on the message headerattribute. For example:

[MessageContract] public class BankingTransaction {  [MessageHeader(Actor=”http://auditingservice.contosobank.com”,MustUnderstand=true)] public bool IsAudited;   [MessageHeader] publicOperation operation;   [MessageBody] public Account sourceAccount;  [MessageBody] public Account targetAccount;   [MessageBody] public intamount; }

Another embodiment allows for controlling these attributes dynamically,e.g., through code. This may be achieved by wrapping the desired headertype in the generic message header type (not to be confused with thenon-generic version) and using the type together with the message headerattribute. Then, properties on the message header can be used to set theSOAP attributes. For example:

[MessageContract] public class BankingTransaction {   [MessageHeader]public MessageHeader<bool> IsAudited;   [MessageHeader] public Operationoperation;   [MessageBody] public Account sourceAccount;   [MessageBody]public Account targetAccount;   [MessageBody] public int amount; } //...application code: BankingTransaction bt = new BankingTransaction( );bt.IsAudited = new MessageHeader<bool>( ); bt.IsAudited.Content = false;//Set IsAudited header value to “false” bt.IsAudited.Actor=”http://auditingservice.contosobank.com”;bt.IsAudited.MustUnderstand=true;If both the dynamic and the static control mechanisms are used,embodiments allow for a default setting (e.g., static settings are usedas a default), which can be overridden using the opposite (e.g.,dynamic) mechanism. For example:

[MessageHeader(MustUnderstand=true)] public MessageHeader<Person>documentApprover; //... later on in the code: BankingTransaction bt =new BankingTransaction( ); bt.documentApprover= newMessageHeader<Person>( ); bt.documentApprover.MustUnderstand=false;//override the static default of ‘true’

Other embodiments also allow for creating repeated headers with dynamicattribute control, for example:

[MessageHeaderArray] public MessageHeader<Person> documentApprovers[];

Occasionally, message contracts may need to change. For example, afuture version of an application may add an extra header to a message.Then, when sending from the new version to the old, an extra header willhave to be dealt with, and going in the other direction there will be amissing header. Embodiments provide for a set of rules for versioningheaders as follows. The serialization/deserialization or messageformatter 230 may not cause an error for missing headers, but rather thecorresponding members may be simply left at their default values.Further, embodiments may ignore extra headers that are not expected. Asmentioned above, the one exception to this rule may be if the extraheader has a MustUnderstand attribute set to true in the incoming SOAPmessage. In this case, an exception may be thrown since a header thatmust be understood cannot be processed.

As described below, other embodiments allow for the modification themessage contract through various configuration mechanisms. Morespecifically, well known mechanisms such as configuration files may beavailable to allow administrators and other users to modify the messagecontract as needed (for example, to accommodate more or less headersdescribed above). In other words, the above embodiments may beprogrammatically implemented, but also supported herein areconfiguration settings that allow these features to be implemented andmodified at deployment time. Such embodiments, therefore, allow for thedecoupling of the developed code from the environment that the code isexecuted in.

Other embodiments allow a message contract type to inherit from anothertype, provided the base type also has a message contract. When creatingor consuming a message using a message contract type that inherits fromother message contract types, the following rules may apply. First,message headers in the inheritance hierarchy can be collected togetherto form the full set of headers for the message. Also, message bodyparts in the inheritance hierarchy can be collected together to form thefull message body. The body parts are ordered according to the usualordering rules (by Order and then alphabetical), with no regards totheir place in the inheritance hierarchy. Next, if a base class and aderived class define a header or a body part with the same name, themember or element from the base-most class will be used to store thevalue of that header or body part.

For example, consider the following classes:

[MessageContract] public class PersonRecord {  [MessageHeader(Name=”ID”)] public int personID;   [MessageBody] publicstring patientName; } [MessageContract] public class PatientRecord :PersonRecord {   [MessageHeader(Name=”ID”)] public int patientID;  [MessageBody] public string diagnosis; }The PatientRecord class describes a message with one header called “ID”.The header corresponds to the personID and not the patientID member,since the base-most member is chosen. Thus, the patientID field isuseless in this case. The body of the message should contain the“diagnosis” element followed by the “patientName” element, since that isthe alphabetical order.

As previously mentioned, the message contract and metadata associatedtherewith can be used to create a NPDL contract, e.g., a WSDL document,XSD document, etc. When generating a WSDL contract from a service thatuses message contracts, note that not all message contract features maybe reflected in the resulting WSDL. Accordingly, the following are somepoints to keep in mind. First, WSDL cannot express the notion of anarray of headers. When creating messages with an array of headers usingthe MessageHeaderArrayAttribute, the resulting WSDL will probably onlyreflect one header instead of the array. Next, some protection levelinformation may not be reflected in the resulting WSDL document. Inaddition, the message type generated in the WSDL may have the same nameas the class name of the message contract type. Something else toconsider is when using the same message contract in multiple operations,multiple message types will be generated in the WSDL document. The namesmay be made unique by adding the numbers “2”, “3”, and so on forsubsequent uses. When importing back the WSDL, multiple message contracttypes can be created, almost identical except for their names.

Note that each message header and message body part is serializedindependently of the others. Therefore, the same namespaces may bere-declared for each header and body part. To improve performance,especially in terms of the size of the message on the wire, embodimentsprovide for consolidating multiple headers and body parts into a singleheader or body part. For example, instead of this:

[MessageContract] public class BankingTransaction {   [MessageHeader]public Operation operation;   [MessageBody] public AccountsourceAccount;   [MessageBody] public Account targetAccount;  [MessageBody] public int amount; }Embodiments can modify the class to this:

  [MessageContract]   public class BankingTransaction   {    [MessageHeader] public Operation operation;     [MessageBody] publicOperationDetails details;   }   [DataContract]   public classOperationDetails   {     [DataMember] public Account sourceAccount;    [DataMember] public Account targetAccount;     [DataMember] publicint amount; }

Another embodiment as described herein allows a user to vary theencoding of a message object rather than being bound to a specific one,e.g., the text encoding for SOAP messaging. As shown in FIG. 1, amessage encoding factory 125, 135 is provided that is responsible formapping a message object (e.g., SOAP Infoset) into raw octets suitablefor wire 130 transmission. By encapsulating the notion of a messageencoder 125, 135 abstractly, embodiments allow users to vary theencoding of an infoset without varying the programming model (or anyother aspect of the system that uses message). In other words,embodiments herein separate the transport (e.g., TCP, HTTP, etc.) fromthe encoding, which allows users to use any number of encodingmechanisms.

For example, a user may wish to use a text-based encoding forinteroperability purposes or a binary-based encoding for performance orother reasons. Alternatively, a user may want to use a MTOM (MessageTransmission Optimization Mechanism) encoding mechanism, which is acombination of XML text and binary, or the user may want to use theirown proprietary encoding. Accordingly, embodiments support any number ofencoding mechanisms and allow the extensibility thereof.

In addition, embodiments also contemplate setting a particular encodingas a default setting when one is not specified by the user. Note thatthe default may be based on the particular transport used. For example,when using HTTP transport XML text-encoding may be set as the default;however, when using TCP, the default may be binary-based encoding. Instill another embodiment, the transport may be automatically chosenbased on a priority level of the transport relative to the encodingselected. For example, if binary-based encoding is selected, TCP ornamed pipes transports might have a higher preference ranking. If theseare not available, however, other transports that are lower ranked maybe used.

The following provides some pseudo-code, tables, and examples forvarious encoding embodiments as described herein. As with otherembodiments, the examples are used for illustrative purposes only andare not meant to limit or otherwise narrow embodiments herein unlessexplicitly claimed.

If a text/XML message encoder is desired for transferring a message(e.g., a service contract) across the wire 130, then no action may benecessary if either HTTP or UDP are used, since these are the defaulttransports for such encoding. If on the other hand TCP, named pipes, orsome other proprietary transport is used, then the message should exposethe encoding by include a text message encoding attribute (note thatother mechanisms for setting the type of encoding are also contemplatedherein). The following table illustrates example priorities that may beset for transports of text/XML-based encoding (note again that theseexample priorities are for illustrative purposes only).

Transport Priority HTTP 1 UDP 1 TCP 3 Named Pipes 3 Custom Transport 2

If a binary-based encoder is desired for transferring a message (e.g., aservice contract) across the wire 130, then no action may be necessaryif either TCP or named pipes are used. If on the other hand HTTP or someother proprietary transport is used, then the message should expose theencoding by include a binary-based encoding attribute. Note that UDP (orsome other transport as the case may be) may not be a supportedtransport for this type of encoding. Nevertheless, as the industryevolves and changes occur (e.g., binary is supported in UDP),embodiments herein allow for the modification to update such prioritybasis. The following table illustrates example priorities that may beset for transports of binary-based encoding (note again that theseexample priorities and unsupported transports are for illustrativepurposes only).

Transport Priority TCP 1 Named Pipes 1 HTTP 3 UDP Not Supported CustomTransport 2

Note that although not specifically called out, other transports may beprioritized for other encoding types (e.g., MTOM). Further note that theprioritizations may be modified by a user based on their own personalpreferences. Accordingly, the above tables that show examples ofprioritized transports based on the type of encoding are used herein forillustrative purposes and are not meant to limit or otherwise narrowsuch embodiments.

Message encoder is a base class for implementations that may support aMIME content type and message version, and serialize/deserializemessages according to that content type. Note that the pseudo-code forthe general message encoder API below uses properties listed in thefollowing table:

Property Description Type CharSet Character Set supported (or “” ifString not applicable). Example: utf8 ContentType Full MIME Content TypeString supported. Example: “application/ soap+xml; charset=’utf8’”MediaType Media Type supported. Example: String “application/soap+xml”MessageVersion Message Version supported MessageVersion (1.1 or 1.2).

The following shows various example message encoder API and bindings inaccordance with example embodiments. Note that, as with otherpseudo-code described herein, any specific use of a particular naming orattribute of an element is for illustrative purposes only and that othersimilar programs may be developed for implementing embodiments describedherein. Accordingly, the following example pseudo-code should not beconstrued to in any way limit embodiments claimed herein.

First Example Message Encoder API

 namespace System.ServiceModel.Channels  { using System;   usingSystem.IO;   public abstract class MessageEncoder   {    // a value like“utf8” (or “” if the format does not support charsets)    publicabstract string CharSet { get; }    // a value like“application/soap+xml; charset=“utf8””.    public abstract stringContentType { get; }    // a value like “application/soap+xml”.   public abstract string MediaType { get; }    public abstractMessageVersion MessageVersion { get; }    public boolIsContentTypeSupported(string contentType)    {     throw newNotImplementedException( );    }    public override string ToString( )   {     throw new NotImplementedException( );    }    // streamedmessage support    public abstract Message ReadMessage(Stream stream,int maxSizeOfHeaders);    public abstract void WriteMessage(Messagemessage, Stream    stream);    // buffered message support    publicabstract Message ReadMessage(ArraySegment<byte> buffer, IBufferManagerbufferManager);    public ArraySegment<byte> WriteMessage(Messagemessage, int maxMessageSize, IBufferManager bufferManager)    {    throw new NotImplementedException( );    }    public abstractArraySegment<byte> WriteMessage(Message message, int maxMessageSize,IBufferManager bufferManager, int messageOffset);   } }

Second Example Message Encoder API

{  using System;  using System.IO;  using System.Net.Mime;  usingSystem.Runtime.Serialization;  using System.ServiceModel.Diagnostics; public abstract class MessageEncoder  {   public abstract stringContentType { get; }   public abstract string MediaType { get; }  public abstract MessageVersion MessageVersion { get; }   publicabstract Message ReadMessage(Stream stream, int maxSizeOfHeaders);  public abstract Message ReadMessage(ArraySegment<byte> buffer,BufferManager bufferManager);   public override string ToString( )   {   throw new NotImplementedException( );   }   public abstract voidWriteMessage(Message message, Stream   stream);   publicArraySegment<byte> WriteMessage(Message message, int maxMessageSize,BufferManager bufferManager)   {    throw new NotImplementedException();   }   public abstract ArraySegment<byte> WriteMessage(Message  message, int maxMessageSize,    BufferManager bufferManager, intmessageOffset);   public virtual bool IsContentTypeSupported(stringcontentType)   {    throw new NotImplementedException( );   }  } }

Example Message Encoding Binding Element

namespace System.ServiceModel.Channels {  usingSystem.Collections.Generic;  using System.ServiceModel.Description; using System.Runtime.Serialization;  using System.ServiceModel;  usingSystem.ServiceModel.Diagnostics;  using System.Xml;  public abstractclass MessageEncodingBindingElement :  BindingElement  {   protectedMessageEncodingBindingElement( )   {   }   protectedMessageEncodingBindingElement(-MessageEncodingBindingElementelementToBeCloned)    :base(elementToBeCloned)   {   }   public abstract AddressingVersionAddressingVersion { get; set; }   public abstract MessageEncoderFactoryCreateMessageEncoderFactory( );   internal protected virtual voidOnImportPolicy(XmlElement assertion, MessageVersion messageVersion,MetadataImporter importer, PolicyConversionContext context) { }  } }

Example Message Encoder Factory

namespace System.ServiceModel.Channels {  using System;  public abstractclass MessageEncoderFactory  {   protected MessageEncoderFactory( )   {  }   public abstract MessageEncoder Encoder   {    get;   }   publicabstract MessageVersion MessageVersion   {    get;   }   public virtualMessageEncoder CreateSessionEncoder( )   {    return Encoder;   }  } }

From the above APIs, the MessageEncodingBindingElement class may beimplemented by each binding element class that represents a requirementto use a particular MessageEncoder in the runtime stack. Further, theinterface may be used to serve as a factory of MessageEncoders.Moreover, note that the properties on MessageEncodingBindingElement maycorrespond directly to the properties on MessageEncoder.

Text message encoder may be used to support a message (e.g., SOAP) overText XML. This may includes support for various versions of the message,e.g., SOAP 1.1 (text/xml) as well as SOAP 1.2 (application/soap+xml).The following table provides some quota considerations give for the textmessage API to follow. As with other specific implementations, these arefor illustrative purposes only.

Quota Description Type Valid values Default MaxWritePoolSize How manyint (1, MaxValue) 16 MessageWriters to pool (each for Streamed,Buffered) MaxReadPoolSize How many int (1, MaxValue) 64 MessageReadersto pool (each for Streamed, Buffered) MaxXmlReaderAllocation The maximumamount of int (1, MaxValue) 16384 memory to allocate in our XML Readers

Example Text Message Encoding Binding Element

namespace System.ServiceModel.Channels {  usingSystem.Collections.Generic;  using System.ServiceModel.Description; using System.Text;  using System.Runtime.Serialization;  usingSystem.ServiceModel.Channels;  using System.ServiceModel;  usingSystem.Xml;  public sealed class TextMessageEncodingBindingElement :MessageEncodingBindingElement, IWsdlExportExtension,IPolicyExportExtension  {   public TextMessageEncodingBindingElement( )   : this(MessageVersion.Default, TextEncoderDefaults.Encoding)   {   }  public TextMessageEncodingBindingElement(MessageVersionmessageVersion, Encoding writeEncoding)   {    throw newNotImplementedException( );   } TextMessageEncodingBindingElement(-TextMessageEncodingBindingElementelementToBeCloned)    :base(elementToBeCloned)   {    throw new NotImplementedException( );   }  public override AddressingVersion AddressingVersion   {    get    {    throw new NotImplementedException( );    }    set    {     throw newNotImplementedException( );    }   }   public int MaxReadPoolSize   {   get    {     throw new NotImplementedException( );    }    set    {    throw new NotImplementedException( );    }   }   public intMaxWritePoolSize   {    get    {     throw new NotImplementedException();    }    set    {     throw new NotImplementedException( );    }   }  public XmlDictionaryReaderQuotas ReaderQuotas   {    get    {    throw new NotImplementedException( );    }   }   publicMessageVersion MessageVersion   {    get    {     throw newNotImplementedException( );    }    set    {     throw newNotImplementedException( );    }   }   public Encoding WriteEncoding   {   get    {     throw new NotImplementedException( );    }    set    {    throw new NotImplementedException( );    }   }   public overrideIChannelFactory<TChannel>  BuildChannelfactory<TChannel>(BindingContextcontext)   {    throw new NotImplementedException( );   }   publicoverride IChannelListener<TChannel>BuildChannelListener<TChannel>(BindingContext context)   {    throw newNotImplementedException( );   }   public override boolCanBuildChannelListener<TChannel>(BindingContext context)   {    thrownew NotImplementedException( );   }   public override BindingElementClone( )   {    throw new NotImplementedException( );   }   publicoverride    MessageEncoderFactory CreateMessageEncoderFactory( )   {   throw new NotImplementedException( );   }   public override TGetProperty<T>(BindingContext context)   {    throw newNotImplementedException( );   }   public voidExportPolicy(MetadataExporter exporter, PolicyConversionContext context)  {    throw new NotImplementedException( );   }   internal protectedoverride void   OnImportPolicy(XmlElement assertion, MessageVersionmessageVersion, MetadataImporter importer, PolicyConversionContextcontext)   {    throw new NotImplementedException( );   }  } }

Note that similar to the general message encoder API, theTextMessageEncodingBiningElement class represents an implementation ofMessageEncodingBindingElement that represents a requirement to use aTextMessageEncoder in the runtime stack. Accordingly, the class mayserve as a factory of TextMessageEncoder instances. Further, theproperties on TextMessageEncodingBiningElement may correspond directlyto the properties on TextMessageEncoder.

The following binary message encoder may be used to support messages(e.g., SOAP) over binary XML. Note that this embodiment may not supportcertain message formats (e.g., SOAP version 1.1) and/or properties(e.g., charset) as those in the text-based encoder. Further, the contenttype is typically application/soap+msbin1. The following table providessome quota considerations give for the text message API to follow. Aswith other specific implementations, these are for illustrative purposesonly.

Quota Description Type Valid values Default MaxWritePoolSize How manyint (1, MaxValue) 16 MessageWriters to pool (each for Streamed,Buffered) MaxReadPoolSize How many int (1, MaxValue) 64 MessageReadersto pool (each for Streamed, Buffered) MaxXmlReaderAllocation The maximumamount of int (1, MaxValue) 16384 memory to allocate in our XML Readers

Example Binary Message Encoding Binding Element

namespace System.ServiceModel.Channels {  using System.Reflection; using System.ServiceModel.Description;  usingSystem.Runtime.Serialization;  using System.ServiceModel;  usingSystem.Xml;  using System.Collections.Generic;  public sealed classBinaryMessageEncodingBindingElement : MessageEncodingBindingElement,IWsdlExportExtension, IPolicyExportExtension  {   publicBinaryMessageEncodingBindingElement( )   {    throw newNotImplementedException( );   }   public override AddressingVersionAddressingVersion   {    get    {     throw new NotImplementedException();    }    set    {     throw new NotImplementedException( );    }   }  public int MaxReadPoolSize   {    get    {     throw newNotImplementedException( );    }    set    {     throw newNotImplementedException( );    }   }   public int MaxWritePoolSize   {   get    {     throw new NotImplementedException( );    }    set    {    throw new NotImplementedException( );    }   }   publicXmlDictionaryReaderQuotas ReaderQuotas   {    get    {     throw newNotImplementedException( );    }  }  public int MaxSessionSize  {   get  {    throw new NotImplementedException( );   }   set   {    throw newNotImplementedException( );   }  }  public overrideIChannelFactory<TChannel> BuildChannelFactory<TChannel>(BindingContextcontext)  {   throw new NotImplementedException( );  }  public overrideIChannelListener<TChannel> BuildChannelListener<TChannel>(BindingContextcontext)  {   throw new NotImplementedException( );  }  public overrideT GetProperty<T>(BindingContext context)  {   throw newNotImplementedException( );  }  public override boolCanBuildChannelListener<TChannel>(BindingContext context)  {   throw newNotImplementedException( );  }  public override BindingElement Clone( ) {   throw new NotImplementedException( );  }  public overrideMessageEncoderFactory CreateMessageEncoderFactory( )  {   throw newNotImplementedException( );  }   public voidExportPolicy(MetadataExporter exporter, PolicyConversionContextpolicyContext)   {    throw new NotImplementedException( );   }  internal protected override void   OnImportPolicy(XmlElementassertion, MessageVersion messageVersion, MetadataImporter importer,PolicyConversionContext policyContext)   {    throw newNotImplementedException( );   }  } }

Similar to the text-based encoder API above, theBinaryMessageEncodingBindingElement class represents an implementationof MessageEncodingBindingElement that represents a requirement to use aBinaryMessageEncoder in the runtime stack. Accordingly, the class mayserve as a factory of BinaryMessageEncoder instances. Further, theproperties on BinaryMessageEncodingBindingElement may corresponddirectly to the properties on BinaryMessageEncoder.

As mentioned above, other transports mechanisms are also supportedherein. For example, the following MTOM message encoding binding may beused to support messages (e.g., SOAP) using such transport.

Example MTOM Message Encoding Binding Element

 namespace System.ServiceModel.Channels {  usingSystem.Collections.Generic;  using System.ServiceModel.Description; using System.Runtime.Serialization;  usingSystem.ServiceModel.Channels;  using System.ServiceModel;  usingSystem.Text;  using System.Xml;  public sealed classMtomMessageEncodingBindingElement : MessageEncodingBindingElement,IWsdlExportExtension, IPolicyExportExtension  {   publicMtomMessageEncodingBindingElement( )    : this(MessageVersion.Default,TextEncoderDefaults.Encoding)   {   }   publicMtomMessageEncodingBindingElement(MessageVersion messageVersion,Encoding writeEncoding)   {    throw new NotImplementedException( );   }  public override AddressingVersion AddressingVersion   {    get    {    throw new NotImplementedException( );    }    set    {     throw newNotImplementedException( );    }   }   public int MaxReadPoolSize   {   get    {     throw new NotImplementedException( );    }    set    {    throw new NotImplementedException( );    }   }   public intMaxWritePoolSize   {    get    {     throw new NotImplementedException();    }    set    {     throw new NotImplementedException( );    }   }  public XmlDictionaryReaderQuotas ReaderQuotas   {    get    {    throw new NotImplementedException( );    }   }   public EncodingWriteEncoding   {    get    {     throw new NotImplementedException( );   }    set    {     throw new NotImplementedException( );    }   }  public MessageVersion MessageVersion   {    get    {     throw newNotImplementedException( );    }    set    {     throw newNotImplementedException( );    }   }   public overrideIChannelFactory<TChannel> BuildChannelFactory<TChannel>(BindingContextcontext)   {    throw new NotImplementedException( );   }   publicoverride bool CanBuildChannelFactory<TChannel>(BindingContext context)  {    throw new NotImplementedException( );   }   public overrideIChannelListener<TChannel> BuildChannelListener<TChannel>(BindingContextcontext)   {    throw new NotImplementedException( );   }   publicoverride bool CanBuildChannelListener<TChannel>(BindingContext context)  {    throw new NotImplementedException( );   }   public overrideBindingElement Clone( )   {    throw new NotImplementedException( );   }  public override MessageEncoderFactory CreateMessageEncoderFactory( )  {    throw new NotImplementedException( );   }   public override TGetProperty<T>(BindingContext context)   {    throw newNotImplementedException( );   }   public voidExportPolicy(MetadataExporter exporter, PolicyConversionContextpolicyContext)   {    throw new NotImplementedException( );   }  internal protected override void OnImportPolicy(XmlElement assertion,MessageVersion messageVersion, MetadataImporter importer,PolicyConversionContext context)   {    throw newNotImplementedException( );   }  } }

Of course, other encoding mechanisms are also contemplated herein.Further, as previously noted, the above APIs use proprietary naming andother features. Nevertheless, any specific encoding mechanism and/orAPIs shown are used herein for illustrative purposes only and is notmeant to limit or otherwise narrow embodiments described herein.

Further note that although the above embodiments (e.g., formatting andencoding) were descried in terms of developer code used to implementthese features, other embodiments also allow for configuration or othersettings that would allow an administrator or other user to implementthese embodiments. For example, the above bindings, encodings,formatters, etc., of services and proxies for messages are modifiablethrough configuration mechanisms. In other words, the above embodimentsmay be programmatically implemented, but also supported herein areconfiguration settings that allow these features to be implemented andmodified at deployment time. Such embodiments, therefore, allow for thedecoupling of the developed code from the environment that the code isexecuted in.

The present invention may also be described in terms of methodscomprising functional steps and/or non-functional acts. The following isa description of steps and/or acts that may be performed in practicingthe present invention. Usually, functional steps describe the inventionin terms of results that are accomplished, whereas non-functional actsdescribe more specific actions for achieving a particular result.Although the functional steps and/or non-functional acts may bedescribed or claimed in a particular order, the present invention is notnecessarily limited to any particular ordering or combination of stepsand/or acts. Further, the use of steps and/or acts is the recitation ofthe claims—and in the following description of the flow diagrams forFIGS. 3-10—typically is used to indicate the desired specific use ofsuch terms.

As previously mentioned, FIGS. 3-10 illustrate flow diagrams for variousexemplary embodiments of the present invention. The followingdescription of FIGS. 3-10 will occasionally refer to correspondingelements from FIGS. 1, 2A, and 2B. Although reference may be made to aspecific element from these Figures, such references are used forillustrative purposes only and are not meant to limit or otherwisenarrow the scope of the described embodiments unless explicitly claimed.

FIG. 3 illustrates a flow diagram for a method 300 of using a singlemessage object to create message instances of multiple messagingformats. Method 300 includes an act of receiving 305 a request to createa message object specific to A first message format. For example,message formatters 120, 145 may receive a request to create a messageobject specific to a versioning of a message (e.g., SOAP 1.1, 1.2).Method 300 also includes an act of accessing 310 a message object thatincludes an envelope. For example, message formatter 120, 145 may accessa message object with an envelope including a first set of fieldsconfigured to include data for elements that correspond to a firstmessage format and a second set of fields configured to include data forelements that correspond to a second message format.

Method 300 also includes a step for populating 315 the first set offields with data for creating an instance of the message object specificto the first format. For instance, message formatters 120, 145 maycreate an instance of a message object specific to a versioning of amessage by populating the fields corresponding to the format desired.Note that in such that some of the fields from other formats or versionsmay not be populated.

Also note that the first set of fields may have overlapping propertieswith the second set of fields such that at least one of the fieldspopulated with data corresponds to a field from the second set offields. In fact, in some cases all of the first set of fields may beincluded within the second set of fields.

FIG. 4A illustrates a flow diagram for a method 400 of simultaneouslyexposing a message infoset as both an XML view and a Type view, whichare synced. Method 400 includes an act of receiving 405 a messageinfoset written using an XML writer. For example, message formatter 120may use an XML writer to create a message infoset, which can be receivedby message formatter 145 at the server 155 (or vice-versa). Note thatthe message infoset will include a common set of headers that exposesvalue(s) as both XML and typed properties. Method 400 also includes anact of retrieving 410 the value(s) using a Typed API. For example, usingthe illustration above, message formatter 145 on the server may use aTyped API, which can read the type properties without regard to how themessage is encoded using XML. Note that the typed properties may be suchthings as URI string values. Also note that the infoset may be a SOAPobject.

FIG. 4B illustrates a flow diagram for another method 450 ofsimultaneously exposing a message infoset as both an XML view and a Typeview. In this embodiment, method 450 includes an act of receiving 455 amessage infoset that includes a common set of headers that exposesvalue(s) as both XML and typed properties, wherein the type propertiesare set using a Typed API. For example, message formatter 145 may use aTyped API to set the type properties on a message infoset, which can bereceived by message formatter 120 at the client 105 (or vice-versa).Method 450 also includes an act of retrieving 410 the value(s) using anXML reader, which reads the type properties as encoded XML. For example,using the illustration above, message formatter 120 on the client 105may use a XML reader to read the type properties set by the Typed API.Note that the typed properties may be such things as URI string values.Also note that the infoset may be a SOAP object.

Note that the retrieval using the XML reader typically include firstidentifying an index to a header using a XML name encapsulating the oneor more values; then retrieving an XML dictionary reader specific to theheader that includes a read operation; and finally passing the header tothe read operation for creating a typed representation of the header.Also note that the XML name may be a qualified name including a name andnamespace.

FIG. 5 illustrates a flow diagram for a method 500 that reduces bufferrequirements for processing a SOAP message by indexing headers as anarray, while still providing random access thereto. Method 500 includesan act of receiving 505 a request to access content of a header from aSOAP message during processing thereof. For example, client 105 orserver 155 may receive a request to access content of a header from aSOAP message 110, 150. Method 500 further includes an act of accessing510 an identifier for the header within an index array. For example,client 105 or server 105 may access an identifier for the header withinan index array, which includes a set of header identifiers used to mapcontent of headers for the SOAP message to a particular location withinan original buffer. Note that the identifier may be a qualified name orsome other unique identifier.

Based on a reference pointer corresponding to the identifier for theheader, method 500 further includes a step for determining 515 alocation for the content within the original buffer. Note that thelocation may be based on the order in which the header appears relativeto other headers within the SOAP message such that the reference pointeris a number of a particular ordering for the header. Further, based onthe determined location, method 500 includes an act of accessing 520 theoriginal buffer for processing at least a portion of the content of theheader without having to store entire content for the set of headeridentifiers as a data structure in an intermediate memory buffer. Notethat not all the headers for the SOAP message may be indexed and thecontent may include attributes, elements, or values.

FIG. 6A illustrates a flow diagram for a method 600 of efficientlyprocessing a SOAP message by attaching properties to a message objectrepresenting processing state of headers for the message. Method 600includes an act of receiving 605 a SOAP message that includes aplurality of headers with content used to process the SOAP message. Forexample, either client 105 or server 155 may receive (e.g., by creatingthe message, or by receiving it from another endpoint) a SOAP messagethat includes a plurality of headers used in processing the SOAPmessage.

Method 600 further includes an act of processing 610 at least a portionof content for a first header from the plurality of headers. Forexample, client 105 or server 155 may process portion(s) of headers forthe message in accordance with any well known manner. Based on theprocessing, method 600 also includes a step for annotating 615 a messageobject with a property representing the processing state for the contentof the first header. For example, upon processing portion(s) of theheaders, client 105 or server 155 may attach or annotate properties on amessage representing processing state for the content such that otheroperations can use the property for further processing of the SOAPmessage.

Note that in some embodiments, the property may be marked to indicatethat either it should or should not persist upon serialization of theSOAP message. This may be done either by the user or automatically bythe system. Note that a default may also be set, e.g., such that aproperty or state information that is not specifically marked is removedor lost upon or before serialization. This may be an appropriatedecision if the message property contains sensitive key information, forinstance.

Similar to above, FIG. 6B illustrates a flow diagram for a method 650 ofefficiently processing a SOAP message by attaching properties to amessage object representing processing state for the SOAP message.Method 650 includes an act of receiving 655 a SOAP message. For example,either client 105 or server 155 may receive (e.g., by creating themessage, or by receiving it from another endpoint) a SOAP message (e.g.,request message 110, response message 150). Method 650 further includesan act of processing 660 at least a portion of the SOAP message. Forexample, client 105 or server 155 may process portion(s) of headers forthe message in accordance with any well known manner. Based on theprocessing, method 600 also includes a step for annotating 665 a messageobject with a property representing the processing state such that otheroperations can use the property for further processing of the SOAPmessage.

Note that the SOAP message may includes header(s) with content, whereinthe property represents processing state of the content for theheader(s). Alternatively, or in conjunction, the SOAP message mayinclude a body portion(s) with content, wherein the property representsprocessing state of the content for the body portion(s). In addition,the property may represents processing state related to environmentalinformation about how a message was received off a communicationconnection.

Further note that similar to above, some embodiments, the property maybe marked to indicate that either it should or should not persist uponserialization of the SOAP message. This may be done either by the useror automatically by the system. Note that a default may also be set,e.g., such that a property or state information that is not specificallymarked is removed or lost upon or before serialization. This may be anappropriate decision if the message property contains sensitive keyinformation, for instance.

FIG. 7 illustrates a flow diagram of a method 700 of formatting a layoutof a message object using a message contract that maps elements tovarious portions thereof. Method 700 includes an act of receiving 705 arequest to create a message object in accordance with a messagecontract. For example, message formatter 230 may receive a request tocreate a message object 240 in accordance with message contract 205,which includes attribute(s) (e.g., header attribute 215, body attribute220, etc.) corresponding to element(s) 210, 225 of a message class.

Method 700 further includes an act of parsing 710 the message contractfor identifying the attribute(s) that define what elements of themessage class map to portion(s) of the message object. Thereafter,method 700 includes an act of populating the portion(s) of the messageobject with the element(s) in accordance with the attribute(s) definedwithin the message contract. More specifically, message formatter 230can parse message contract 205 for identifying the attribute(s) (e.g.,header attribute 215, body attribute 220, etc.) that define whatelements 210, 225 of the message class map to portions(s) of the messageobject 240. Once the attribute(s) are identified, the appropriateportions(s) of the message object 240 can be populated with thecorresponding element(s) 210, 225.

For example, elements 210 corresponding to a header attribute 215 shouldbe populated in the header portion of the message object 240. Similarly,those elements 225 corresponding to a body attribute 220 should bepopulated in the body portion of the message object. Note that theelement(s) may include the following forms type, struct, field,property, or operation.

FIG. 8 illustrates a flow diagram for a method 800 of creating aninstance of a message object by using a message contract that mapselements to various portions thereof. Method 800 includes an act ofreceiving 805 a request to create an instance of a message object inaccordance with a message contract. For example, similar to above,message formatter 230 may receive a request to create a message object240 in accordance with message contract 205, which includes attribute(s)(e.g., header attribute 215, body attribute 220, etc.) corresponding toelement(s) 210, 225 of a message class.

Method 800 further includes an act of parsing 810 the message contractfor identifying the attribute(s) that define what elements of themessage class map to portion(s) of the message object. Further, method800 includes an act of receiving 815 value(s) corresponding to theelement(s). Thereafter, method 800 includes an step for crating 820 aninstance of the message object by populating the portion(s) of themessage object with the value(s) in accordance with the attribute(s)defined within the message contract. More specifically, messageformatter 230 can parse message contract 205 for identifying theattribute(s) (e.g., header attribute 215, body attribute 220, etc.) thatdefine what elements 210, 225 of the message class map to portions(s) ofthe message object 240. Further, message formatter 230 may receivemessage values 245 such that once the attribute(s) are identified, theappropriate portions(s) of the message object 240 can be populated withthe corresponding values(s) 210, 225 for creating an instance 250 of anoutput message.

FIG. 9 illustrates a flow diagram for a method 900 of automaticallycreating one or more portions of an NPDL contract used by clients incommunicating with a service. Method 900 includes an act of receiving905 a request to create a NPDL contract. For example, a NPDL modulewithin server 155 may receive a request to create a NPDL contract (e.g.,a WSDL document), which defines how a client 105 is to communicate witha service 155. Further, method 900 includes an act of receiving 910 amessage contract. For example, the NPDL module may receive messagecontract 205, which includes attribute(s) (e.g., header attributes 215,body attributes 220) corresponding to element(s) 215, 225 of a messageclass.

Based on the received message contract, method 900 also includes a stepfor creating 915 at least a portion of the NPDL contract by specifyingwhere and what elements should be included in a message object orinstance thereof when communicating with the service. More specifically,upon receiving the message contract 205, the NPDL contract module mayautomatically create a NPDL contract 275, which at least a portionthereof is based on the message contract 205 and stored in contractstore 280. Note that similar embodiments as those described above withregard to message contract 205 may also apply to this embodiment.

FIG. 10 illustrates a flow diagram for a method 950 of determining atype of encoding to use for a SOAP message, without requiring only atext-based encoding. Method 950 includes an act of receiving 955 a SOAPmessage typically bound to a text-based transport encoding forcommunicating between two endpoints. For example, message encoderfactories 125, 135 may receive a SOAP message typically bound to atext-based transport encoding. Method 950 further includes an act ofselecting 960 an encoding type from a plurality of encodings based on aprogram and/or configuration setting. For example, message encoderfactories 125, 135 may select a binding or encoding mechanism from aplurality of encodings including text-based, binary based, MTOM, or someproprietary encoding.

Thereafter, method 950 includes a step for encoding 965 the SOAP messagewith the selected encoding for transferring over a communicationchannel. For example, after selecting the type of encoding, encoders125, 135 can encode a SOAP message in accordance therewith forcommunication and other purposes. Note, that the selection of atransport may also be based on the selected encoding. For instance, thetransports may include TCP/IP, HTTP, UDP, or a proprietary transport.Further note that the selection of the transport may also be based on apriority ranking set for each of the plurality of transport settings orby a default setting.

Also note that when a proprietary encoding is used, such encoder canencode the SOAP message into an alternative message format other thanSOAP. For example, the SOAP message may be formatted into an alternativemessage format such as SMTP, MSMQ, etc.

The present invention may be embodied in other specific forms withoutdeparting from its spirit or essential characteristics. The describedembodiments are to be considered in all respects only as illustrativeand not restrictive. The scope of the invention is, therefore, indicatedby the appended claims rather than by the foregoing description. Allchanges which come within the meaning and range of equivalency of theclaims are to be embraced within their scope.

1. In a distributed messaging system, a method of efficiently sendinglarge messages by limiting the amount of the message that is loaded intoan intermediate buffer before sending across a wire to a destinationnode, the method comprising: accessing a message that is to be sentacross the wire to a destination node; loading a first portion of themessage into an intermediate buffer for random access thereto;formatting a second portion of the message, different from the firstportion, in the form of a transport stream; and streaming the secondportion of the message across a wire to the destination node withoutloading the second portion in the intermediate buffer in order to reducebuffer requirements for sending large messages.
 2. The method of claim1, wherein the message is a SOAP message and the first portion includesone or more headers, and the second portion is an attachment within abody of the message.
 3. The method of claim 1, wherein the streaming ofthe second portion is done using a transport connection that isdedicated to stream the message.
 4. The method of claim 3, wherein thetype of transport supports exchange patterns of one or morerequest/reply channel, output/input channel, or full duplex channel. 5.The method of claim 3, wherein upon sending the message the methodfurther comprises: closing the transport connection in order to notifythe destination node that the transmission is complete.
 6. The method ofclaim 3, wherein the transport connection is one of a TCP socket, namedpipe, or HTTP connection.
 7. The method of claim 6, wherein the clientis configured to send the message across one of the transportconnections using a transfer mode property of a channel factory.
 8. Themethod of claim 6, wherein the client is configured to send the messageacross one of the transport connections using a transport bindingelement.
 9. In a distributed messaging system, a computer programproduct for implementing a method of efficiently sending large messagesby limiting the amount of the message that is loaded into anintermediate buffer before sending across a wire to a destination node,the computer program product comprising one or more computer readablemedia having stored thereon computer executable instructions that, whenexecuted by a processor, can cause the distributed messaging system toperform the following: access a message that is to be sent across thewire to a destination node; load a first portion of the message into anintermediate buffer for random access thereto; format a second portionof the message, different from the first portion, in the form of atransport stream; and stream the second portion of the message across awire to the destination node without loading the second portion in theintermediate buffer in order to reduce buffer requirements for sendinglarge messages.
 10. The computer program product of claim 9, wherein themessage is a SOAP message and the first portion includes one or moreheaders, and the second portion is an attachment within a body of themessage.
 11. The computer program product of claim 9, wherein thestreaming of the second portion is done using a transport connectionthat is dedicated to stream the message.
 12. The computer programproduct of claim 11, wherein the type of transport supports exchangepatterns of one or more request/reply channel, output/input channel, orfull duplex channel.
 13. The computer program product of claim 11,wherein upon sending the message the computer program product furthercomprises computer executable instructions that cause the distributedmessaging system to perform the following: close the transportconnection in order to notify the destination node that the transmissionis complete.
 14. The computer program product of claim 11, wherein thetransport connection is one of a TCP socket, named pipe, or HTTPconnection.
 15. The computer program product of claim 14, wherein theclient is configured to send the message across one of the transportconnections using a transfer mode property of a channel factory.
 16. Thecomputer program product of claim 14, wherein the client is configuredto send the message across one of the transport connections using atransport binding element. 17-26. (canceled)